//
//  VWPlayerLoadingStateLayer.swift
//  VideoPlayer_Example
//
//  Created by JY_NEW on 2021/10/14.
//  Copyright © 2021 CocoaPods. All rights reserved.
//
import ijkPlayerManager
import UIKit
import UICreate

/// 加载状态
class VWPlayerLoadingStateLayer: VWPlayerBaseLayer {
    
    override var category: VideoPlayerLayerCategory {
        return .state
    }
    
    let speedMonitor = NetworkSpeedMonitor()
    
    override init() {
        super.init()
        NotificationCenter.default.addObserver(self, selector: #selector(self.onSpeedChanged), name: .init(rawValue: NetworkDownloadSpeedNotificationKey), object: nil)
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func loadPlayerManager(_ player: VideoPlayerManagerType) {
        player.observer.status.addTarget( self, action: #selector(self.onStatusChanged))
    }
    override func unloadPlayerManager(_ player: VideoPlayerManagerType) {
        player.observer.status.removeTarget(self)
    }
    
    override func loadContainerView(_ containerView: UIView) {
        containerView.add(self.contentView, layout: .center)
    }
    
    @objc func onStatusChanged() {
        if let player = self.playerManager, player.status.isBuffering || player.status.isPreparingWithPlay {
            self.active()
        }else{
            self.deactive()
        }
    }
    
    @objc func onSpeedChanged() {
        self.speedLabel.text = self.speedMonitor.downloadNetworkSpeed
    }
    
    override func show(completion: @escaping () -> Void) {
        self.aniamteShow(for: self.contentView, completion: completion)
        loadingView.start()
        self.speedMonitor.start()
    }
    override func hide(completion: @escaping () -> Void) {
        self.aniamteHide(for: self.contentView, completion: completion)
        loadingView.stop()
        self.speedMonitor.stop()
    }
    
    // MARK: 界面控件
    lazy var contentView: UIView = {
        let contentView = UIView()
        
        contentView.add {
            loadingView.layout(.top, .marginX)
            speedLabel.layout(.bottomTop(12))
                .layout(for: .parent, .centerX, .bottom)
        }
        return contentView
    }()
    
    lazy var loadingView: LoadingView = LoadingView()
    
    lazy var speedLabel: UILabel = UILabel(.text(""), .font(.pingfang(medium: 10)), .color(.white))
}

extension VWPlayerLoadingStateLayer {
    class LoadingView: UIView {
        let gradientLayer = CAGradientLayer()
        let shapeLayer = CAShapeLayer()
        let speed: CGFloat = 1
        let lineWidth: CGFloat = 2
        private(set) var isAnimating = false
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            
            gradientLayer.startPoint = .init(1)
            gradientLayer.endPoint = .zero
            gradientLayer.locations = [0, 0.3, 0.5, 1]
            gradientLayer.colors = [UIColor(white: 0.01, alpha: 0.01).cgColor,
                                    UIColor(white: 1, alpha: 0.25).cgColor,
                                    UIColor(white: 1, alpha: 1).cgColor]
            
            shapeLayer.strokeColor = UIColor.systemBlue.cgColor
            shapeLayer.fillColor = UIColor.clear.cgColor
            shapeLayer.strokeStart = 0.15
            shapeLayer.strokeEnd = 0.8
            shapeLayer.lineCap = .round
            shapeLayer.lineWidth = lineWidth

            self.layer.addSublayer(self.gradientLayer)
            self.gradientLayer.mask = self.shapeLayer
            self.alpha = 0.001
        }
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        override var intrinsicContentSize: CGSize {
            return (38)
        }
        override func layoutSubviews() {
            super.layoutSubviews()
            let width = min(self.bounds.size.width, self.bounds.size.height)
            let height = width
            self.gradientLayer.bounds = [0, 0, width, height]
            self.gradientLayer.position = .init(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5)
            self.shapeLayer.position = .init(lineWidth, lineWidth)
            self.shapeLayer.path = UIBezierPath(arcCenter: .init(width * 0.5 - lineWidth, height * 0.5 - lineWidth), radius: (width - lineWidth) * 0.5, startAngle: 0, endAngle: .pi * 2, clockwise: true).cgPath
        }
        func start() {
            if self.isAnimating { return }
            self.isAnimating = true
            self.alpha = 1
            if self.gradientLayer.animation(forKey: "rotation") == nil {
                let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")
                rotationAnim.toValue = CGFloat.pi * 2
                rotationAnim.duration = self.speed
                rotationAnim.repeatCount = MAXFLOAT
                rotationAnim.isRemovedOnCompletion = false
                self.gradientLayer.add(rotationAnim, forKey: "rotation")
            }
        }
        func stop() {
            if !self.isAnimating { return }
            self.isAnimating = false
            UIView.animate(withDuration: 0.3) {
                self.alpha = 0.001
            } completion: { _ in
                if !self.isAnimating {
                    self.gradientLayer.removeAnimation(forKey: "rotation")
                }
            }
        }
    }
}
